package urjc.as.emergencies.resources;

import org.restlet.Context;
import org.restlet.data.Form;
import org.restlet.data.MediaType;
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.restlet.data.Status;
import org.restlet.resource.Representation;
import org.restlet.resource.ResourceException;
import org.restlet.resource.Variant;

import urjc.as.emergencies.data.PatientInfo;

public class PatientInfoResource extends BaseResource {

	public PatientInfoResource(Context context, Request request,
			Response response) {
		super(context, request, response);
		// Variantes de representación soportadas
		getVariants().add(new Variant(MediaType.TEXT_XML));
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.restlet.resource.Resource#allowDelete()
	 */
	@Override
	public boolean allowDelete() {
		return false;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.restlet.resource.Resource#allowGet()
	 */
	@Override
	public boolean allowGet() {
		return true;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.restlet.resource.Resource#allowPost()
	 */
	@Override
	public boolean allowPost() {
		return false;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.restlet.resource.Resource#allowPut()
	 */
	@Override
	public boolean allowPut() {
		return true;
	}

	public boolean allowPatch() {
		return true;
	}

	/* (non-Javadoc)
	 * @see org.restlet.resource.Resource#storeRepresentation(org.restlet.resource.Representation)
	 */
	@Override
	public void storeRepresentation(Representation entity)
			throws ResourceException {
		
		try {
			if (entity.getMediaType().equals(MediaType.TEXT_XML)) {
				// Inicializa la misión
				String xmlInfoPatient = getRequest().getEntity().getText();
				PatientInfo infoPatient = (PatientInfo) PatientInfo.deserializar(xmlInfoPatient);

				// Almaceno
				getStorage().addEntity(infoPatient);
				getResponse().setLocationRef(infoPatient.getUri());
			} else {
				throw new ResourceException(
						Status.CLIENT_ERROR_UNSUPPORTED_MEDIA_TYPE);
			}

			// Si todo va bien, envía: (201 -- Created)
			getResponse().setStatus(Status.SUCCESS_CREATED);
		} catch (Exception e) {
			// Si saltan excepciones porque el destinatario no existe,
			// entonces:
			throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST);
		}
	}
	
	// Handlers

	public void handlePatch() throws ResourceException {
		getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);

		// 1) Obtenemos el recurso misión
		PatientInfo patientInfo = (PatientInfo) getStorage().getEntity(
				getRequest().getResourceRef().getBaseRef().toString());

		// 2) Procesamos el patch
		Form form = getRequest().getEntityAsForm();

		// 2.1 Es un patch para el diagnóstico
		String diagnosis = form.getFirstValue(PatientInfo.DIAGNOSIS);
		if (diagnosis != null) {
			patientInfo.setDiagnostico(diagnosis);
			getResponse().setStatus(Status.SUCCESS_OK);
		}
		// 2.2 Es un patch para el nombre
		String name = form.getFirstValue(PatientInfo.NAME);
		if (name != null) {
			patientInfo.setName(name);
			getResponse().setStatus(Status.SUCCESS_OK);
		}
		// 2.1 Es un patch para el diagnóstico
		String sex = form.getFirstValue(PatientInfo.SEX);
		if (sex != null) {
			patientInfo.setSex(sex);
			getResponse().setStatus(Status.SUCCESS_OK);
		}
		// 2.1 Es un patch para la edad
		String ageS = form.getFirstValue(PatientInfo.AGE);
		if (ageS != null) {
			try {
				int age = Integer.parseInt(ageS);
				if (age < 1 || age > 130) {
					getResponse().setStatus(
							new Status(Status.CLIENT_ERROR_BAD_REQUEST,
									"Edad no valida"));
					return;
				}
				patientInfo.setEdad(age);
				getResponse().setStatus(Status.SUCCESS_OK);
			} catch (Exception e) {
				getResponse().setStatus(
						new Status(Status.CLIENT_ERROR_BAD_REQUEST,
								"Edad no valida"));
				return;
			}
		}
		

	}

}
